package com.perfect.service;

/**
 * @author YU
 */

import com.perfect.base.BaseService;
import com.perfect.dao.OrdersMapper;
import com.perfect.model.OrdersModel;
import com.perfect.utils.AssertUtil;
import com.perfect.vo.Orders;
import com.perfect.vo.Post;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrdersService extends BaseService<Orders, Integer> {

    @Resource
    private OrdersMapper ordersMapper;


    /**
     * 订单发货
     * @param post
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void sendOd(Post post){
        AssertUtil.isTrue(checkParamsIsBlank(post),"参数错误");
        post.setPrice(20d);
        AssertUtil.isTrue(checkParamsIsBlank(post.getOdId()),"参数错误");
        Orders orders = ordersMapper.selectOrderByOdId(post.getOdId());
        AssertUtil.isTrue(orders == null,"没有找到相应订单");
        AssertUtil.isTrue(ordersMapper.insertPost(post) < 1,"订单发货失败");
        AssertUtil.isTrue(ordersMapper.updateOrdersPostByOdId(post.getId(),post.getOdId()) < 1,"订单发货失败");
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    public OrdersModel selectOrderModel(Integer id){
        AssertUtil.isTrue(checkParamsIsBlank(id),"订单id为空");
        OrdersModel model = ordersMapper.selectOrderModel(id);
        AssertUtil.isTrue(model == null,"没有查到相应订单");
        return model;
    }

    /**
     * 删除订单
     * @param id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteOrders(Integer id){
        AssertUtil.isTrue(checkParamsIsBlank(id),"请选择要删除的订单");
        AssertUtil.isTrue(selectByPrimaryKey(id) == null,"待删除记录不存在");
        AssertUtil.isTrue(deleteByPrimaryKey(id) < 1,"删除订单失败");
    }

    /**
     * 删除多条记录
     * @param ids
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteMoreOrders(String ids){
        AssertUtil.isTrue(checkParamsIsBlank(ids),"请选择要删除的订单");
        int count = 0;
        String[] id = ids.split(",");
        for (String i : id){
            deleteOrders(Integer.parseInt(i));
            count++;
        }
        AssertUtil.isTrue(id.length < count,"删除订单失败");
    }

    /**
     * 参数的非空判断
     * @param params
     * @return
     */
    public boolean checkParamsIsBlank(Object ...params){
        for (Object o : params){
            if (o == null){
                return true;
            }
            if (o instanceof String){
                if (o == null || o == ""){
                    return true;
                }
            }
        }
        return false;
    }
}
